import { Platform, Alert } from 'react-native';
import { GLOBAL } from '../../config/global';
import HTTP from '../../utils/http';
import { API, API_GENERATE } from '../../config/api';
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
var appInfo = require('react-native-device-info');

class AppUpdate {

  checkingUpdate = false;

  checkUpdate = () => {
    return new Promise(async (resolve) => {
      let info = null;
      if (!GLOBAL.IS_EMULATOR && !this.checkingUpdate) {
        this.checkingUpdate = true;
        let versionInfo = await HTTP.GET(API_GENERATE(API.GET_UPDATE_INFO), { suitPlatform: Platform.OS });
        StorageHelper.set(STORAGE_CONSTANT.APP_VERSION_INFO, versionInfo);
        this.checkingUpdate = false;
        if (versionInfo && versionInfo.suitPlatform && versionInfo.suitPlatform.toLowerCase() == Platform.OS && versionInfo.versionCode) {
          let update = await this.versionCompare(versionInfo);
          if (update) info = versionInfo
        }
      }
      resolve(info)
    });
  }

  async versionCompare (versionInfo) {
    let currVersion = appInfo.getBuildNumber(); // 当前版本
    let latestVersion = versionInfo['versionCode']; // 最新版本
    let ignoreInfo = await StorageHelper.get(STORAGE_CONSTANT.VERSION_IGNORE);
    ignoreInfo = JSON.parse(ignoreInfo) || {}
    let ignoreVersion = ignoreInfo['versionIgnoreCode'] || 1; // 忽略更新的版本
    // 最新版本 > 当前版本 判断是否需要更新
    // 忽略的版本号 == 最新版本 不提示更新
    if (currVersion && latestVersion && parseFloat(latestVersion) > parseFloat(currVersion)) {
      GLOBAL.APP_HAS_UPDATE = true;
      if (ignoreVersion && parseFloat(ignoreVersion) == parseFloat(latestVersion)) return
      return true
    }
    return false
  }
}
module.exports = new AppUpdate();
